<?php


namespace app\api\service;
use app\api\model\Order as OrderModel;
use app\api\model\Product as ProductModel;
use app\api\service\Order as OrderService;
use app\enum\OrderStatusEnum;
use Exception;
use think\facade\Db;
use think\facade\Log;


spl_autoload_register('auto_load_class'); //spl注册自动加载

class WxNotify extends \WxPayNotify
{
    /**
     * @param \WxPayNotifyResults   $objData
     * @param \WxPayConfigInterface $config
     * @param string                $msg
     *
     * @return bool
     */
    public function NotifyProcess($objData, $config, &$msg): bool
    {
        if($objData['result_code']=='SUCCESS'){
            $orderNo = $objData['out_trade_no'];
            Db::startTrans();
            try{
                $order = OrderModel::where('order_no','=',$orderNo)->find();
                if($order->status == 1){
                    $service = new OrderService();
                    $stockStatus = $service->checkOrderStock($order->id);
                    if($stockStatus['pass']){
                        $this->updateOrderStatus($order->id,true);
                        $this->reduceStock($stockStatus);
                    }else{
                        $this->updateOrderStatus($order->id,false);
                    }
                }
                Db::commit();
                return true;
            }catch (Exception $ex){
                Db::rollback();
                Log::error($ex);
                return false;
            }
        }
        return true;
    }

    private function updateOrderStatus($orderID,$success)
    {
        $status  =$success?OrderStatusEnum::PAID:OrderStatusEnum::PAID_BUT_OUT_OF;
        OrderModel::where('id','=',$orderID)->update(['status'=>$status]);
    }

    private function reduceStock($statusStatus)
    {
        foreach ($statusStatus['pStatusArray'] as $singlePStatus){
            Db::table('product')->where('id','=',$singlePStatus['id'])
                ->dec('stock',$singlePStatus['count'])->update();
        }
    }

}